/**
 * 
 */
package me.twoday.library.mine.common.network;

import java.util.ArrayList;

import me.twoday.library.mine.common.LoggerUtil;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;

/**
 * HTTP POST 요청에 사용되는 클래스
 * 
 * @author 박우람
 * @since 2011.02.13
 */
public class HttpPostConnection extends HttpConnection
{
	private static final String TAG = "HttpPostConnection";
	private static final String DEFAULT_CHARACTER_SET = "UTF-8";
	private final LoggerUtil mLog;
	private ArrayList<NameValuePair> mParams;
	
	/**
	 * 기본이 되는 생성자.
	 * 
	 * @param httpHandler 처리 핸들러
	 */
	public HttpPostConnection(HttpHandler httpHandler)
	{
		super(httpHandler);
		this.mParams = new ArrayList<NameValuePair>();
		this.mLog = LoggerUtil.getInstance(TAG);
	}
	
	/**
	 * 문자열 형태의 파라미터를 입력합니다.
	 * 
	 * @param name 파라미터명
	 * @param value 파라미터값
	 */
	public void putParam(String name, String value)
	{
		mParams.add(new BasicNameValuePair(name, value));
	}
	
	/**
	 * 정수 형태의 파라미터를 입력합니다.
	 * 
	 * @param name 파라미터명
	 * @param value 파라미터값
	 */
	public void putParam(String name, int value)
	{
		mParams.add(new BasicNameValuePair(name, Integer.toString(value)));
	}
	
	/* (non-Javadoc)
	 * @see com.starpl.platform.common.network.HttpConnection#run()
	 */
	@Override
	public void run()
	{
		try
		{
			executePreProcess();
			HttpPost httpPost = new HttpPost(mUrl);
			httpPost.setEntity(new UrlEncodedFormEntity(mParams, DEFAULT_CHARACTER_SET));
			httpPost.setHeader("Cookie", getCookieSessionKey());
			mLog.d("Http Request(POST): " + mUrl + " { " + httpPost.getEntity().toString() + " }");
			
			boolean hasEntity = executePostProcess(mHttpClient.execute(httpPost));
			if(hasEntity)
			{
				httpPost.abort();
			}
		}
		catch(Exception e)
		{
			processNetworkError(e);
		}
	}
}
